package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.conf.LoadCloumnsConfig;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Discription: 通知回传淘宝发货接口
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/12/7 17:27
 */
@Component
@Slf4j
public class LogisticsSendService {

    @Autowired
    private SendMqServies sendMq;
    @Autowired
    private ChangelogsticsStatusService changelogsticsStatusService;
    @Autowired
    private LoadCloumnsConfig loadCloumnsConfig;
    @Autowired
    private PropertiesConf pconf;
    @Autowired
    private LocalLogService localLogService;

    /**
     * 发货状态回传启动函数
     */
    public void logisticsStart() {
        // 获取自身 bean
        LogisticsSendService logisticsSendService = ApplicationContextHandle.getBean(LogisticsSendService.class);
        logisticsSendService.loginSend();
    }

    /**
     * 查询确认发货状态表
     *
     * @throws Exception
     */
    @Transactional
    public void loginSend() {

        try {
            // 查询上限
            int rownums = pconf.getPropertyInt("ons.pushorderNum");
            // 查询回流表数据
            String countSql = "select * from T_OMS_OrderOutStorage where syncstatus = 0 and platform in (2,3) and  rownum <= " + rownums + " order by " +
                    "id for update skip locked";
            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);
            // 有需要回流的数据 将查询到的数据以消息形式发送
            if (jsonArr == null || jsonArr.isEmpty()) {
                log.debug("OrderOutStorage Order jsonArr is null");
                return;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",jsonArr.toJSONString());
            jsonObject.put("tag",pconf.getProperty("ons.comp"));
            sendMq.sendMqinfoObj(jsonObject, pconf.getProperty("ons.logsticTopic", "TAOBAO_ORDER_LOGISTIC"), pconf.getProperty("ons.comp", "burgeon"));
            // 更改确认发货表同步状态
            changelogsticsStatusService.changeStatus1(jsonArr);

        } catch (Exception e) {
            //  同步发货状态出现异常
            log.error("同步发货订单失败");

        }

    }

}
